# This file is part of GPropertyGrid project. 
# The COPYRIGHT file at the top level of this repository 
# contains the full copyright notices and license terms.

from gi.repository import Gtk, Gdk
from . propertygridproperty import PropertyGridProperty

class PropertyColor(PropertyGridProperty):
    def __init__(self, name, id=None, default=None, 
                    description=None, force_value=False):
    
        hbox=Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        self._txt=Gtk.Entry()
        self._txt.connect("changed", self.on_txt_changed)
        
        self._buttom = Gtk.ColorButton()
        self._buttom.set_use_alpha(True)
        self._buttom.connect("color_set", self.on_toggled)
        
        hbox.pack_start(self._buttom, True, True, 0)
        hbox.pack_start(self._txt, True, True, 0)        
        
        super(PropertyColor, self).__init__(name=name, value_widget=hbox,
                            id=id,
                            default=default, 
                            description=description, 
                            force_value=force_value)
                            
        self.set_value_text(default)
        
        color = self.get_color_from_str(default)
        if color:
            self._buttom.set_rgba(color)
        self._txt.set_text(default)

    def get_color_from_str(self, str_color):
        if str_color == None:
            return
        color = Gdk.RGBA()
        if color.parse(str_color):
            return color
            
    def get_gdk_rgba(self):
        if self.value:
            return self._buttom.get_rgba()

    def on_toggled(self, wg):
        self._txt.set_text(self._buttom.get_rgba().to_string())
        
    def on_txt_changed(self, wg):
        self.on_change()

    def on_leave(self):
        pass

    def on_change(self):
        if not super(PropertyColor, self).on_change():
            return False
        
        color = self.get_color_from_str(self._txt.get_text())
        if color:
            self._buttom.set_rgba(color)
            self.value=self._txt.get_text()
        else:
            self._buttom.set_rgba(Gdk.RGBA())
            self.value=None            
        self.set_value_text(self.value)
        self.has_changed=True        
        return True
        
